// 通过问卷答案生成报告
import {request} from "./http-base";
import * as api from "../apis";
import {Questionnaire} from "../types";

type QuestionDes = {
  answerIds: number[], // 答案 ID
  itemId: number,// questionID
  other: string
}

type GenerateReportRequest = {
  items: QuestionDes[] | [],
  pageId: number,// 问卷 ID
}

export const generateReport = async (questionnaire: Questionnaire) => {
  let postData: GenerateReportRequest;
  postData = {
    pageId: questionnaire.id,
    items: [],
  };
  // 组装 QuestionDes
  /// 抽出问卷中的所有问题
  /// 拿到每个问题中的 selectedOption
  let questionDescList : Array<QuestionDes> = [];
  questionnaire.items.forEach(question=>{
    if(!question.selectedOptions){
      return;
    }
    // “其他”选项的ID不需要传递给后端
    let selectedAnswerIds = question.selectedOptions.filter(item => !item.other).map(item=>item.id);
    questionDescList.push({
      itemId:question.id,
      answerIds:selectedAnswerIds,
      other: question.other || ''
    })
  });
  postData.items = questionDescList;
  return request(api.generateReport, postData, "POST");
}
